package com.quan.upms.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.quan.base.common.exception.AuthorizationException;
import com.quan.base.common.utils.IpHelper;
import com.quan.base.common.utils.date.DateUtils;
import com.quan.sso.common.pojo.SSOUser;
import com.quan.sso.common.tools.UserHolder;
import com.quan.upms.annotation.RequiresPermissions;

/**
 * 权限验证拦截器
 * 
 * @author yhaoquan
 * 
 */
public class AuthInterceptorAdapter extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(AuthInterceptorAdapter.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		try {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			RequiresPermissions permissions = handlerMethod.getMethodAnnotation(RequiresPermissions.class);

			boolean isPermissioin = false;

			if (null != permissions) {// 权限验证
				//当前登录用户信息
				SSOUser user = UserHolder.getUser() ;
				
				// 超级管理员，直接通过
				if (null != user && null != user.getIsAdmin() && user.getIsAdmin()) {
					return true;
				}
				
				// 鉴权
				if (user.getPermissions().contains(permissions.value())) {
					isPermissioin = true;
				}

			} else {// 没有权限注解，不需验证权限，直接通过
				return true;
			}

			if (isPermissioin) { // 鉴权通过
				return true;
			} else { // 鉴权不通过
				logger.info("验证权限==》不通过, 用户：{}, IP：{}, 方法：{}, 操作描述：{}, 权限：{}, 时间：{}", UserHolder.getRealName(), IpHelper.getIpAddr(request), handlerMethod.getMethod().getDeclaringClass().getCanonicalName() + "." + method.getName(), permissions.description(), permissions.value(), DateUtils.getDateTime());
				throw new AuthorizationException("权限不足，操作描述["+permissions.description()+"]，权限[" + permissions.value() + "]");
			}
		} catch (Exception e) {
			throw new Exception("登录超时或未登录，无法获取当前用户登录信息") ;
		}
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
}
